<template>
  <view class="coupon-center">
    <!-- 轮播图 -->
    <swiper class="banner-swiper" indicator-dots autoplay circular>
      <swiper-item v-for="(banner, index) in banners" :key="index">
        <image :src="banner.image" class="banner-image" @click="handleBannerClick(banner)" />
      </swiper-item>
    </swiper>

    <!-- 快捷入口 -->
    <view class="quick-actions">
      <view class="action-item" @click="goToCouponList">
        <view class="action-icon">🎫</view>
        <text class="action-text">我的券包</text>
      </view>
      <view class="action-item" @click="goToGroup">
        <view class="action-icon">👥</view>
        <text class="action-text">拼券团</text>
      </view>
      <view class="action-item" @click="goToBlindBox">
        <view class="action-icon">🎁</view>
        <text class="action-text">盲盒任务</text>
      </view>
      <view class="action-item" @click="goToPoints">
        <view class="action-icon">⭐</view>
        <text class="action-text">积分商城</text>
      </view>
    </view>

    <!-- 个性化推荐 -->
    <view class="recommendation-section">
      <view class="section-header">
        <text class="section-title">为你推荐</text>
        <text class="section-subtitle">基于AI智能推荐</text>
      </view>
      <scroll-view scroll-x class="recommendation-scroll">
        <view class="recommendation-item" v-for="coupon in recommendedCoupons" :key="coupon.id" @click="handleCouponClick(coupon)">
          <view class="coupon-card">
            <view class="coupon-header">
              <text class="coupon-name">{{ coupon.name }}</text>
              <view class="coupon-tag" v-if="coupon.isPersonalized">个性化</view>
            </view>
            <view class="coupon-value">
              <text class="value-text">{{ formatCouponValue(coupon) }}</text>
            </view>
            <view class="coupon-threshold">
              <text class="threshold-text">满{{ coupon.threshold }}可用</text>
            </view>
            <view class="coupon-footer">
              <text class="expire-text">{{ formatExpireTime(coupon.validEndTime) }}</text>
              <button class="receive-btn" @click.stop="receiveCoupon(coupon)">立即领取</button>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 热门券 -->
    <view class="hot-coupons-section">
      <view class="section-header">
        <text class="section-title">热门券</text>
        <text class="more-text" @click="goToAllCoupons">更多 ></text>
      </view>
      <view class="coupon-grid">
        <view class="coupon-item" v-for="coupon in hotCoupons" :key="coupon.id" @click="handleCouponClick(coupon)">
          <view class="coupon-card">
            <view class="coupon-type-tag">{{ getCouponTypeText(coupon.type) }}</view>
            <view class="coupon-name">{{ coupon.name }}</view>
            <view class="coupon-value">{{ formatCouponValue(coupon) }}</view>
            <view class="coupon-threshold">满{{ coupon.threshold }}可用</view>
            <view class="coupon-stock">
              <text class="stock-text">剩余{{ coupon.remainingStock }}张</text>
            </view>
            <button class="receive-btn" @click.stop="receiveCoupon(coupon)">领取</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 拼券团推荐 -->
    <view class="group-section" v-if="groupCoupons.length > 0">
      <view class="section-header">
        <text class="section-title">拼券团</text>
        <text class="more-text" @click="goToGroup">更多 ></text>
      </view>
      <view class="group-list">
        <view class="group-item" v-for="group in groupCoupons" :key="group.id" @click="goToGroupDetail(group.id)">
          <view class="group-info">
            <text class="group-title">{{ group.couponName }}</text>
            <text class="group-desc">{{ group.targetSize }}人团，立享{{ group.rewardMultiplier }}倍奖励</text>
          </view>
          <view class="group-progress">
            <text class="progress-text">{{ group.currentSize }}/{{ group.targetSize }}</text>
            <button class="join-btn" @click.stop="joinGroup(group.id)">立即参团</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 盲盒任务 -->
    <view class="blindbox-section" v-if="blindBoxTasks.length > 0">
      <view class="section-header">
        <text class="section-title">盲盒任务</text>
        <text class="more-text" @click="goToBlindBox">更多 ></text>
      </view>
      <view class="task-list">
        <view class="task-item" v-for="task in blindBoxTasks" :key="task.id" @click="goToTaskDetail(task.id)">
          <view class="task-icon">🎁</view>
          <view class="task-info">
            <text class="task-name">{{ task.name }}</text>
            <text class="task-desc">{{ task.description }}</text>
          </view>
          <view class="task-reward">
            <text class="reward-text">奖励池: {{ task.rewardPoolSize }}</text>
            <button class="start-btn" @click.stop="startTask(task.id)">开始任务</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      banners: [
        {
          id: 1,
          image: '/static/banner1.jpg',
          link: '/pages/coupon/list'
        },
        {
          id: 2,
          image: '/static/banner2.jpg',
          link: '/pages/group/index'
        }
      ],
      recommendedCoupons: [],
      hotCoupons: [],
      groupCoupons: [],
      blindBoxTasks: [],
      loading: false
    }
  },
  
  onLoad() {
    this.loadData()
  },
  
  onPullDownRefresh() {
    this.loadData().then(() => {
      uni.stopPullDownRefresh()
    })
  },
  
  methods: {
    async loadData() {
      this.loading = true
      try {
        await Promise.all([
          this.loadRecommendedCoupons(),
          this.loadHotCoupons(),
          this.loadGroupCoupons(),
          this.loadBlindBoxTasks()
        ])
      } catch (error) {
        console.error('加载数据失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    async loadRecommendedCoupons() {
      try {
        const response = await uni.request({
          url: '/api/ai/personalized-coupons',
          method: 'GET',
          data: {
            userId: this.getUserId(),
            limit: 5
          }
        })
        this.recommendedCoupons = response.data.data || []
      } catch (error) {
        console.error('加载推荐券失败:', error)
      }
    },
    
    async loadHotCoupons() {
      try {
        const response = await uni.request({
          url: '/api/coupon/hot',
          method: 'GET',
          data: {
            limit: 6
          }
        })
        this.hotCoupons = response.data.data || []
      } catch (error) {
        console.error('加载热门券失败:', error)
      }
    },
    
    async loadGroupCoupons() {
      try {
        const response = await uni.request({
          url: '/api/group/active',
          method: 'GET',
          data: {
            limit: 3
          }
        })
        this.groupCoupons = response.data.data || []
      } catch (error) {
        console.error('加载拼券团失败:', error)
      }
    },
    
    async loadBlindBoxTasks() {
      try {
        const response = await uni.request({
          url: '/api/blindbox/tasks',
          method: 'GET',
          data: {
            limit: 3
          }
        })
        this.blindBoxTasks = response.data.data || []
      } catch (error) {
        console.error('加载盲盒任务失败:', error)
      }
    },
    
    handleBannerClick(banner) {
      uni.navigateTo({
        url: banner.link
      })
    },
    
    handleCouponClick(coupon) {
      uni.navigateTo({
        url: `/pages/coupon/detail?id=${coupon.id}`
      })
    },
    
    async receiveCoupon(coupon) {
      try {
        uni.showLoading({
          title: '领取中...'
        })
        
        const response = await uni.request({
          url: '/api/coupon/receive',
          method: 'POST',
          data: {
            userId: this.getUserId(),
            couponId: coupon.id
          }
        })
        
        uni.hideLoading()
        
        if (response.data.code === 200) {
          uni.showToast({
            title: '领取成功',
            icon: 'success'
          })
          // 更新券的剩余库存
          coupon.remainingStock--
        } else {
          uni.showToast({
            title: response.data.message || '领取失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: '领取失败',
          icon: 'none'
        })
      }
    },
    
    async joinGroup(groupId) {
      try {
        uni.showLoading({
          title: '加入中...'
        })
        
        const response = await uni.request({
          url: '/api/group/join',
          method: 'POST',
          data: {
            groupId: groupId,
            userId: this.getUserId()
          }
        })
        
        uni.hideLoading()
        
        if (response.data.code === 200) {
          uni.showToast({
            title: '加入成功',
            icon: 'success'
          })
          // 刷新拼券团数据
          this.loadGroupCoupons()
        } else {
          uni.showToast({
            title: response.data.message || '加入失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: '加入失败',
          icon: 'none'
        })
      }
    },
    
    async startTask(taskId) {
      try {
        uni.showLoading({
          title: '开始任务...'
        })
        
        const response = await uni.request({
          url: '/api/blindbox/start-task',
          method: 'POST',
          data: {
            taskId: taskId,
            userId: this.getUserId()
          }
        })
        
        uni.hideLoading()
        
        if (response.data.code === 200) {
          uni.showToast({
            title: '任务开始',
            icon: 'success'
          })
          // 跳转到任务详情页
          uni.navigateTo({
            url: `/pages/blindbox/task?id=${taskId}`
          })
        } else {
          uni.showToast({
            title: response.data.message || '开始失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: '开始失败',
          icon: 'none'
        })
      }
    },
    
    goToCouponList() {
      uni.switchTab({
        url: '/pages/coupon/list'
      })
    },
    
    goToGroup() {
      uni.switchTab({
        url: '/pages/group/index'
      })
    },
    
    goToBlindBox() {
      uni.navigateTo({
        url: '/pages/blindbox/index'
      })
    },
    
    goToPoints() {
      uni.navigateTo({
        url: '/pages/user/points'
      })
    },
    
    goToAllCoupons() {
      uni.navigateTo({
        url: '/pages/coupon/all'
      })
    },
    
    goToGroupDetail(groupId) {
      uni.navigateTo({
        url: `/pages/group/detail?id=${groupId}`
      })
    },
    
    goToTaskDetail(taskId) {
      uni.navigateTo({
        url: `/pages/blindbox/task?id=${taskId}`
      })
    },
    
    formatCouponValue(coupon) {
      switch (coupon.type) {
        case 'DIRECT_REDUCTION':
        case 'FULL_REDUCTION':
          return `¥${coupon.value}`
        case 'DISCOUNT':
          return `${(coupon.value * 10).toFixed(1)}折`
        case 'GIFT':
          return '赠品券'
        case 'LADDER':
          return '阶梯券'
        default:
          return `¥${coupon.value}`
      }
    },
    
    getCouponTypeText(type) {
      const typeMap = {
        'FULL_REDUCTION': '满减券',
        'DISCOUNT': '折扣券',
        'DIRECT_REDUCTION': '立减券',
        'GIFT': '赠品券',
        'LADDER': '阶梯券'
      }
      return typeMap[type] || type
    },
    
    formatExpireTime(expireTime) {
      const now = new Date()
      const expire = new Date(expireTime)
      const diffDays = Math.ceil((expire - now) / (1000 * 60 * 60 * 24))
      
      if (diffDays <= 0) {
        return '已过期'
      } else if (diffDays === 1) {
        return '明天过期'
      } else {
        return `${diffDays}天后过期`
      }
    },
    
    getUserId() {
      // 从本地存储获取用户ID
      return uni.getStorageSync('userId') || '1'
    }
  }
}
</script>

<style scoped>
.coupon-center {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.banner-swiper {
  height: 200px;
  margin-bottom: 20px;
}

.banner-image {
  width: 100%;
  height: 100%;
}

.quick-actions {
  display: flex;
  justify-content: space-around;
  background-color: #fff;
  padding: 20px 0;
  margin-bottom: 20px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.action-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.action-text {
  font-size: 12px;
  color: #666;
}

.recommendation-section,
.hot-coupons-section,
.group-section,
.blindbox-section {
  background-color: #fff;
  margin-bottom: 20px;
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.section-subtitle {
  font-size: 12px;
  color: #999;
}

.more-text {
  font-size: 14px;
  color: #007aff;
}

.recommendation-scroll {
  white-space: nowrap;
}

.recommendation-item {
  display: inline-block;
  width: 280px;
  margin-right: 15px;
}

.coupon-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 20px;
  color: #fff;
  position: relative;
  overflow: hidden;
}

.coupon-card::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 20px;
  height: 20px;
  background-color: #f5f5f5;
  border-radius: 50%;
  transform: translate(10px, -10px);
}

.coupon-card::after {
  content: '';
  position: absolute;
  bottom: 0;
  right: 0;
  width: 20px;
  height: 20px;
  background-color: #f5f5f5;
  border-radius: 50%;
  transform: translate(10px, 10px);
}

.coupon-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.coupon-name {
  font-size: 16px;
  font-weight: bold;
}

.coupon-tag {
  background-color: rgba(255, 255, 255, 0.2);
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 10px;
}

.coupon-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.coupon-threshold {
  font-size: 12px;
  opacity: 0.8;
  margin-bottom: 15px;
}

.coupon-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.expire-text {
  font-size: 12px;
  opacity: 0.8;
}

.receive-btn {
  background-color: rgba(255, 255, 255, 0.2);
  color: #fff;
  border: none;
  padding: 6px 12px;
  border-radius: 15px;
  font-size: 12px;
}

.coupon-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.coupon-item .coupon-card {
  background: #fff;
  color: #333;
  border: 1px solid #e0e0e0;
}

.coupon-type-tag {
  background-color: #007aff;
  color: #fff;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 10px;
  margin-bottom: 8px;
  display: inline-block;
}

.coupon-item .coupon-name {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 5px;
}

.coupon-item .coupon-value {
  font-size: 18px;
  font-weight: bold;
  color: #ff6b6b;
  margin-bottom: 5px;
}

.coupon-item .coupon-threshold {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.coupon-stock {
  margin-bottom: 10px;
}

.stock-text {
  font-size: 12px;
  color: #999;
}

.coupon-item .receive-btn {
  background-color: #007aff;
  color: #fff;
  border: none;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 12px;
  width: 100%;
}

.group-list,
.task-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.group-item,
.task-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.group-info,
.task-info {
  flex: 1;
}

.group-title,
.task-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.group-desc,
.task-desc {
  font-size: 12px;
  color: #666;
}

.group-progress,
.task-reward {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.progress-text,
.reward-text {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.join-btn,
.start-btn {
  background-color: #007aff;
  color: #fff;
  border: none;
  padding: 6px 12px;
  border-radius: 15px;
  font-size: 12px;
}

.task-icon {
  font-size: 24px;
  margin-right: 15px;
}
</style>
